rest = require("rest")
Config = require("../config")

url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Config.appId + "&secret=" + Config.secret;

exports.gGetToken = ->

    gGetToken = ->
        data = yield rest(url)
        data = JSON.parse(data.entity)
        value = data.access_token
        startTime = Date.now()
        global.weixin ?= {}
        global.weixin.token =
            value: value
            startTime: startTime
        console.log("token:" + global.weixin.token.value)
        global.weixin.token

    if global.weixin?.token
        startTime = global.weixin.startTime
        currentTime = Date.now()
        time = currentTime - startTime
        if (time > 1.5 * 60 * 60) # 1.5小时后过期
            yield from gGetToken()
        else
            console.log("stored token" + global.weixin.token.value)
            yield global.weixin.token
    else
        yield from gGetToken()

